//
//  MFWDownloadDBHelp.m
//  TravelGuideMdd
//
//  Created by 陈曦 on 13-7-8.
//  Copyright (c) 2013年 mafengwo.com. All rights reserved.
//

#import "MFWDownloadDBHelp.h"
#import "MFWDownloadManager.h"
#import "FMDatabase.h"

#define DEFAULT_CATALOG_NAME @"MFWDownloadDBHelpDefaultCatalogName"

@interface MFWDownloadDBHelp()

@property (nonatomic, retain) FMDatabase *db;
@property (nonatomic, copy)NSString *dbPath;

@end

@implementation MFWDownloadDBHelp

- (void)printAll
{
    return;
    NSString *sql = @"select * from DownloadTasks";
    [self openDB];
    FMResultSet *set = [self.db executeQuery:sql];
    NSMutableString *string = [[NSMutableString alloc] init];
    while (set.next) {
        [string appendString:@"\n"];
        for (NSUInteger i = 0 ;i < set.columnCount;i++)
        {
            [string appendFormat:@"%@\n",[set stringForColumnIndex:i]];
        }
    }
    NSLog(@"db %@",string);
    [self closeDB];
}

- (void)createDB
{
    if (![self openDB])
    {
        return;
    }
    NSString *Sql = @"CREATE TABLE IF NOT EXISTS DownloadTasks(ID text,URL text,LocalPath text,TempPath text,State smallint,PRIMARY KEY (ID))";
    [self.db executeUpdate:Sql];
    
    Sql = @"CREATE TABLE IF NOT EXISTS UserInfo(ID text,KeyName text,strValue text,intValue text)";
    [self.db executeUpdate:Sql];

    Sql = @"CREATE TABLE IF NOT EXISTS _t_meta ("
    @"c_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT"
    @",c_db_version INTEGER"
    @",c_ctime TIMESTAMP DEFAULT (datetime('now','localtime'))"
    @",c_description TEXT"
    @")";
    [self.db executeUpdate:Sql];
    
    [self closeDB];
}

- (int)latestDBVersion
{
    if (![self openDB])
    {
        return -1;
    }
    
    NSString *sql = @"SELECT * FROM _t_meta ORDER BY c_ctime DESC limit 1";
    FMResultSet *resultSet = [self.db executeQuery:sql];
    int version = -1;
    while (resultSet.next)
    {
        version = [resultSet intForColumn:@"c_db_version"];
    }
    [self closeDB];
    
    return version;
}

+ (BOOL)setDBVersion:(NSString*)verision widthDescription:(NSString*)desc db:(FMDatabase *)db
{
    if (verision == nil)
    {
        verision = @"0";
    }
    
    if (desc == nil)
    {
        desc = @"";
    }
    
    NSString *sql = [NSString stringWithFormat:@"INSERT OR IGNORE INTO _t_meta (c_db_version, c_description) VALUES('%@', '%@');", verision, desc];
    
    return [db executeUpdate:sql];
}

- (MFWDownloadDBHelp*)initWithPath:(NSString *)aPath
{
    self = [super init];
    if(self)
    {
        self.db = [FMDatabase databaseWithPath:aPath];
        _dbPath = [aPath copy];

        [self createDB];
    }
    return self;
}

- (BOOL)openDB
{
    return [self.db open];
}

- (BOOL)closeDB
{
    return [self.db close];
}

- (void)updateState:(MFWDownloadState)aState withID:(NSString *)aID
{
    if(![self openDB])
    {
        return;
    }
    
    NSString *sql = [NSString stringWithFormat:@"update DownloadTasks set state=%d where ID='%@'",aState,aID];
    
    [self.db executeUpdate:sql];
    [self closeDB];
    
    [self printAll];
}

+ (NSString*)relativeHomePathForAbsulutePaht:(NSString*)absPath
{
    NSString *homePath = NSHomeDirectory();
    return [absPath stringByReplacingOccurrencesOfString:homePath withString:@""];
}

- (void)addItem:(MFWDownloadItem *)aItem
{
    NSString *aID = aItem.uuid;
    NSString *aURL = aItem.url;
    NSString *aTempPath = aItem.tempPath;
    NSString *aLocalPath = aItem.localPath;
    MFWDownloadState aState = aItem.state;
    
    NSString *relativeHomeTempPath = [MFWDownloadDBHelp relativeHomePathForAbsulutePaht:aTempPath];
    NSString *relativeHomeLocalPath = [MFWDownloadDBHelp relativeHomePathForAbsulutePaht:aLocalPath];
    
    NSString *sql = [NSString stringWithFormat:@"\
  insert into DownloadTasks(ID  ,URL ,LocalPath ,TempPath ,State)\
                     values('%@','%@','%@'      ,'%@'     ,   %d)" ,
                            aID ,aURL,relativeHomeLocalPath,relativeHomeTempPath,aState];
    if(![self openDB])
    {
        return;
    }
    [self.db executeUpdate:sql];
    [self closeDB];
    [self printAll];
}

- (void)removeByID:(NSString*)aID
{
    if (![self openDB])
    {
        return;
    }
     NSString *sql = [NSString stringWithFormat:@"\
                      delete from DownloadTasks where ID='%@'",aID];
    [self.db executeUpdate:sql];
    [self closeDB];
    [self printAll];
}

- (NSArray*)getAllItems
{
    if (![self openDB])
    {
        return nil;
    }
    
    // 取得所有的item 
    NSString *sql = [NSString stringWithFormat:@"select * from DownloadTasks"];
    FMResultSet *set = [self.db executeQuery:sql];
    
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    while ([set next]) {
        NSString *relativeTempPath = [set stringForColumn:@"TempPath"];
        NSString *relativeLocalPath = [set stringForColumn:@"LocalPath"];
        
        MFWDownloadItem *item = [[MFWDownloadItem alloc] init];
        item.tempPath = [NSString stringWithFormat:@"%@/%@", NSHomeDirectory(), relativeTempPath];
        item.localPath = [NSString stringWithFormat:@"%@/%@", NSHomeDirectory(), relativeLocalPath];
        item.state = [set intForColumn:@"State"];
        item.url = [set stringForColumn:@"URL"];
        item.uuid = [set stringForColumn:@"ID"];
        [arr addObject:item];
        [dict setValue:item forKey:item.uuid];
    }
    
    sql = [NSString stringWithFormat:@"select * from UserInfo"];
    
    FMResultSet *infoSet = [self.db executeQuery:sql];
    while ([infoSet next]) {
        NSString *ID = [infoSet stringForColumn:@"ID"];
        MFWDownloadItem *item = [dict valueForKey:ID];
        if (item)
        {
            if (!item.userInfo)
            {
                item.userInfo = [[NSMutableDictionary alloc] init];
            }
            [item.userInfo setValue:[infoSet stringForColumn:@"Value"]
                             forKey:[infoSet stringForColumn:@"KeyName"]];
        }
    }
    
    dict = nil;
    
    [self closeDB];
    return arr;
}

@end
